package com.mulanweb.filter;

import com.jfinal.kit.StrKit;
import com.mulanweb.db.common.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户登录控制过滤器
 * Created by hcy on 2016/3/21.
 */
public class AdminLoginFilter implements Filter {

    private static List<String> excludePatternList = new ArrayList<String>();

    public void init(FilterConfig filterConfig) throws ServletException {

        String contextPath = filterConfig.getServletContext().getContextPath();
        String excludePatternStr = filterConfig.getInitParameter("excludePattern");
        if (StrKit.notBlank(excludePatternStr)) {
            String[] excludePatterns = excludePatternStr.split(",");
            for (String pattern : excludePatterns) {
                excludePatternList.add(".*" + contextPath + pattern.trim().replace("*", ".*"));
            }
        }

    }

    /**
     * 是否为排除登录验证资源
     *
     * @param requestUrl 请求路径
     * @return 如果不需要登录验证返回true，否则返回false
     */
    private boolean isExcludeResource(String requestUrl){
        for (String pattern : excludePatternList) {
            if (requestUrl.matches(pattern)) {
                return true;
            }
        }
        return false;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (isExcludeResource(request.getRequestURI()) || (request.getSession().getAttribute(Constant.XinXiLan.ADMIN_LOGIN_TAG) != null &&request.getSession().getAttribute(Constant.XinXiLan.ADMIN_LOGIN_TAG) =="yes")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect(Constant.XinXiLan.SELLER_LOGIN_URL);
        }
    }

    public void destroy() {

    }
}
